package id.ac.amikom.amikomsocial;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import id.ac.amikom.libs.AdemDBHelper;
import id.ac.amikom.libs.AdemServiceHelper;
import id.ac.amikom.libs.HttpFileUploader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AdemLoginActivity extends Activity implements LocationListener {

	private static final int RESULT_LOAD_IMAGE = 1;
	private AdemDBHelper db = null;
	private AdemServiceHelper srv;
	private Cursor c;

	private Button btnLogin, btnLogout, btnProfile;
	private EditText txtId, txtPwd;
	private TextView viewId, viewName, viewSts, viewLog, viewLoc;
	private ImageView viewImg;
	private String uid, id, pwd;
	private String value = null;

	protected LocationManager location;

	public class UploadTask extends AsyncTask<String, Void, Boolean> {

		private ProgressDialog dialog = new ProgressDialog(AdemLoginActivity.this);
		String out;

		protected void onPreExecute() {
			dialog.setMessage("Uploading..");
			dialog.show();
		}

		protected void onPostExecute(Boolean result) {
			this.dialog.dismiss();

			String imgPath = "";
			boolean exists = (new File("/mnt/sdcard/amikom/amikom_user.png"))
					.exists();
			if (exists) {
				imgPath = "/mnt/sdcard/amikom/amikom_user.png";
			} else {
				imgPath = "/mnt/sdcard/amikom/amikom_user.jpg";
			}

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 2;
			Bitmap bmp = BitmapFactory.decodeFile(imgPath, options);
			viewImg.setImageBitmap(bmp);

			Toast.makeText(AdemLoginActivity.this, out, Toast.LENGTH_LONG)
					.show();

		}

		@Override
		protected Boolean doInBackground(String... params) {

			try {
				HttpFileUploader htfu = new HttpFileUploader(
						AdemLoginActivity.this,
						"http://amikomsocial.com/service/srvimg",
						"noparamshere", "/mnt/sdcard/amikom/amikom_user.png");
				out = htfu.doStart();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

			return null;
		}

	}

	public class LogoutTask extends AsyncTask<String, Void, Boolean> {

		private ProgressDialog dialog = new ProgressDialog(AdemLoginActivity.this);

		protected void onPreExecute() {
			dialog.setMessage("Logout..");
			dialog.show();
		}

		protected void onPostExecute(Boolean result) {
			dialog.dismiss();
			if (result == true) {
				Toast.makeText(AdemLoginActivity.this,
						"Logout Success, Calendar and Elearning data deleted",
						Toast.LENGTH_LONG).show();

				Intent i = new Intent(AdemLoginActivity.this,
						AdemTabActivity.class);
				i.putExtra("url", "");
				startActivity(i);

				finish();
			}
		}

		@Override
		protected Boolean doInBackground(String... params) {

			Uri eventUri;
			if (Build.VERSION.SDK_INT >= 8)
				eventUri = Uri.parse("content://com.android.calendar/events");
			else
				eventUri = Uri.parse("content://calendar/events");

			Cursor c = getContentResolver().query(eventUri, null, null, null,
					null);

			if (c.moveToFirst()) {
				while (c.moveToNext()) {
					String location = c.getString(c
							.getColumnIndex("eventLocation"));
					String id = c.getString(c.getColumnIndex("_id"));
					String loc = "" + location;

					if (loc.equals("STMIK Amikom") || loc.contains("Amikom")) {

						Uri uri = ContentUris.withAppendedId(eventUri,
								Integer.parseInt(id));
						getContentResolver().delete(uri, null, null);
					}
				}
			}

			File fs = new File("/mnt/sdcard/amikom/amikom_user.jpg");
			fs.delete();

			File ff = new File("/mnt/sdcard/amikom/amikom_user.png");
			boolean ifs = ff.exists();
			if (ifs) {
				ff.delete();
			}

			db.deleteLogin();
			db.deleteCalendar();
			db.deleteMateri();
			db.deleteShout();

			return true;
		}

	}

	public class BackGroundTask extends AsyncTask<String, Void, Boolean> {

		private ProgressDialog dialog = new ProgressDialog(AdemLoginActivity.this);
		String fotoUrl;

		protected void onPreExecute() {
			dialog.setMessage("Login as " + id + "..");
			dialog.show();
		}

		protected void onPostExecute(Boolean result) {
			dialog.dismiss();
			if (result == true) {
				Toast.makeText(AdemLoginActivity.this, "Login Success",
						Toast.LENGTH_LONG).show();

				Intent i = new Intent(AdemLoginActivity.this,
						AdemTabActivity.class);
				i.putExtra("url", fotoUrl);

				startActivity(i);
				finish();

			} else {
				Toast.makeText(AdemLoginActivity.this, "Login Failed",
						Toast.LENGTH_LONG).show();
			}

		}

		protected Boolean doInBackground(String... params) {
			AdemServiceHelper srv = new AdemServiceHelper(
					AdemLoginActivity.this);
			if (srv.login(id, pwd)) {
				//srv.getCalendarService();
				fotoUrl = srv.getFotoUrl();

				return true;
			} else {
				return false;
			}

		}

	}

	public class EditUserTask extends AsyncTask<String, Void, Boolean> {

		ProgressDialog dialog = new ProgressDialog(AdemLoginActivity.this);
		boolean result = false;
		String text = null;

		@Override
		protected Boolean doInBackground(String... params) {

			AdemServiceHelper srv = new AdemServiceHelper(
					AdemLoginActivity.this);
			text = srv.editUser(uid, value);

			db.updateAlias(uid, value);

			return true;
		}

		protected void onPreExecute() {
			this.dialog.setMessage("Edit Username..");
			this.dialog.show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			Toast.makeText(AdemLoginActivity.this, text, Toast.LENGTH_LONG)
					.show();

			this.dialog.dismiss();

		}
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		db = new AdemDBHelper(this);
		srv = new AdemServiceHelper(getApplicationContext());
		c = db.getLogin();

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		if (c.getCount() > 0) {
			setContentView(R.layout.adem_profile);

			btnProfile = (Button) findViewById(R.id.btnEdit);
			btnLogout = (Button) findViewById(R.id.btnLogout);
			viewId = (TextView) findViewById(R.id.viewId);
			viewName = (TextView) findViewById(R.id.viewName);
			viewSts = (TextView) findViewById(R.id.viewSts);
			viewLog = (TextView) findViewById(R.id.viewLog);
			viewLoc = (TextView) findViewById(R.id.viewLoc);
			viewImg = (ImageView) findViewById(R.id.viewImg);

			String id = "", name = "", sts = "", log = "";
			if (c.moveToFirst()) {
				do {

					uid = c.getString(c.getColumnIndex("usr"));

					String identity = "";
					int status = Integer.parseInt(c.getString(c
							.getColumnIndex("is_mhs")));
					if (status == 1)
						identity = "Amikom Student";
					else if (status == 2)
						identity = "Amikom Lecturer";
					else
						identity = "Amikom Alumni";

					id = "Id User. " + c.getString(c.getColumnIndex("usr"));
					name = "Name User. "
							+ c.getString(c.getColumnIndex("name"));
					sts = "Status User. " + identity;

					log = "Login Date. "
							+ c.getString(c.getColumnIndex("logdate"));
				} while (c.moveToNext());
			}

			viewId.setText(id);
			viewName.setText(name);
			viewSts.setText(sts);
			viewLog.setText(log);

			String imgPath = "";
			boolean exists = (new File("/mnt/sdcard/amikom/amikom_user.png"))
					.exists();
			if (exists) {
				imgPath = "/mnt/sdcard/amikom/amikom_user.png";
			} else {
				imgPath = "/mnt/sdcard/amikom/amikom_user.jpg";
			}

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 2;
			Bitmap bmp = BitmapFactory.decodeFile(imgPath, options);
			viewImg.setImageBitmap(bmp);

			viewImg.setOnClickListener(new View.OnClickListener() {

				public void onClick(View arg0) {
					Intent i = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

					// i.putExtra("crop", "true");
					startActivityForResult(i, RESULT_LOAD_IMAGE);

				}
			});

			btnProfile.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					AlertDialog.Builder alert = new AlertDialog.Builder(
							AdemLoginActivity.this);
					alert.setTitle("Edit Userame");

					LayoutInflater factory = LayoutInflater
							.from(AdemLoginActivity.this);
					View textEntryView = factory.inflate(
							R.layout.adem_dialog_user, null);
					final EditText postText = (EditText) textEntryView
							.findViewById(R.id.user_txt);

					alert.setView(textEntryView);

					alert.setPositiveButton("Save",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									value = postText.getText().toString();
									new EditUserTask().execute();

								}
							});

					alert.show();

				}
			});

			btnLogout.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					new LogoutTask().execute();

					db.close();
				}
			});

		} else {

			setContentView(R.layout.adem_login);

			btnLogin = (Button) findViewById(R.id.btnLog);
			txtId = (EditText) findViewById(R.id.inputId);
			txtPwd = (EditText) findViewById(R.id.inputPwd);

			btnLogin.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					id = txtId.getText().toString();
					pwd = txtPwd.getText().toString();

					new BackGroundTask().execute();

					db.close();

				}

			});

		}

		c.close();
		db.close();

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.adem_title);

		location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		Location loc = location
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (loc != null) {
		} else {
			loc = location.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		}

		this.onLocationChanged(loc);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);

			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			Uri filePathUri = Uri.parse(cursor.getString(column_index));
			String fileName = filePathUri.getLastPathSegment().toString();

			Log.i("picture name....", fileName);
			Log.i("picture path....", picturePath);

			cursor.close();

			try {
				int inWidth = 0;
				int inHeight = 0;
				int dstWidth = 150;
				int dstHeight = 150;

				String pathOfInputImage = picturePath;
				String pathOfOutputImage = "/mnt/sdcard/amikom/amikom_user.png";

				InputStream is = new FileInputStream(pathOfInputImage);

				// decode image size (decode metadata only, not the whole image)
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				BitmapFactory.decodeStream(is, null, options);
				is.close();
				is = null;

				// save width and height
				inWidth = options.outWidth;
				inHeight = options.outHeight;

				// decode full image pre-resized
				is = new FileInputStream(pathOfInputImage);
				options = new BitmapFactory.Options();
				// calc rought re-size (this is no exact resize)
				options.inSampleSize = Math.max(inWidth / dstWidth, inHeight
						/ dstHeight);
				// decode full image
				Bitmap roughBitmap = BitmapFactory.decodeStream(is, null,
						options);

				// calc exact destination size
				Matrix m = new Matrix();
				RectF inRect = new RectF(0, 0, roughBitmap.getWidth(),
						roughBitmap.getHeight());
				RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
				m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
				float[] values = new float[9];
				m.getValues(values);

				// resize bitmap
				Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap,
						(int) (roughBitmap.getWidth() * values[0]),
						(int) (roughBitmap.getHeight() * values[4]), true);

				// save image
				try {
					FileOutputStream out = new FileOutputStream(
							pathOfOutputImage);
					resizedBitmap
							.compress(Bitmap.CompressFormat.JPEG, 100, out);

					//Log.i("type-->", getMimeType(pathOfOutputImage)+" "+pathOfOutputImage);

					new UploadTask().execute();

				} catch (Exception e) {
					Log.e("Image", e.getMessage(), e);
				}
			} catch (IOException e) {
				Log.e("Image", e.getMessage(), e);
			}

		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		location.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				1000 * 60 * 30, 1000, this);
		//location.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
		//		1000 * 60 * 30, 1000, this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// location.removeUpdates(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			Intent i = new Intent(AdemLoginActivity.this, AdemTabActivity.class);
			i.putExtra("url", "");
			startActivity(i);
			finish();

			return false;

		}
		return super.onKeyDown(keyCode, event);
	}

	public void onLocationChanged(Location loc) {
		double lat = 0;
		double lon = 0;

		if (loc != null) {
			lat = loc.getLatitude();
			lon = loc.getLongitude();
		}

		Geocoder geocoder = new Geocoder(this, Locale.getDefault());

		try {
			String location = "";
			List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);

			if (addresses != null && addresses.size() > 0) {
				Address returnedAddress = addresses.get(0);
				String addr = "";
				for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
					addr = addr + " " + returnedAddress.getAddressLine(i);
				}

				location = addr.trim();
				srv.updateActivity(location, lat, lon);

				Log.i("Location", location);

				if (c.getCount() > 0) {
					viewLoc.setText("Location. " + location);
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	public static String getMimeType(String url) {
		String type = null;
		String extension = MimeTypeMap.getFileExtensionFromUrl(url);
		if (extension != null) {
			MimeTypeMap mime = MimeTypeMap.getSingleton();
			type = mime.getMimeTypeFromExtension(extension);
		}
		return type;
	}

}
